#!/usr/bin/env python3
"""
离线语言播放系统演示启动脚本
"""

import os
import sys
import webbrowser
import threading
import time
from pathlib import Path

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

def check_dependencies():
    """检查依赖是否安装"""
    required_packages = [
        ('fastapi', 'fastapi'),
        ('uvicorn', 'uvicorn'),
        ('pydantic', 'pydantic'),
        ('python-multipart', 'multipart'),
        ('jinja2', 'jinja2')
    ]
    
    missing_packages = []
    for package_name, import_name in required_packages:
        try:
            __import__(import_name.replace('-', '_'))
        except ImportError:
            missing_packages.append(package_name)
    
    if missing_packages:
        print("❌ 缺少以下依赖包:")
        for package in missing_packages:
            print(f"   - {package}")
        print("\n请运行以下命令安装依赖:")
        print(f"pip install {' '.join(missing_packages)}")
        return False
    
    print("✅ 所有依赖已安装")
    return True

def start_backend():
    """启动后端服务"""
    try:
        print("🚀 启动后端服务...")
        
        # 导入并启动FastAPI应用
        from app.main import app
        import uvicorn
        
        # 在新线程中启动服务
        def run_server():
            uvicorn.run(
                app,
                host="127.0.0.1",
                port=8000,
                log_level="info",
                access_log=False
            )
        
        server_thread = threading.Thread(target=run_server, daemon=True)
        server_thread.start()
        
        # 等待服务启动
        time.sleep(3)
        
        # 检查服务是否启动成功
        import requests
        try:
            response = requests.get("http://127.0.0.1:8000/health/", timeout=5)
            if response.status_code == 200:
                print("✅ 后端服务启动成功!")
                return True
            else:
                print("❌ 后端服务启动失败")
                return False
        except:
            print("❌ 无法连接到后端服务")
            return False
            
    except Exception as e:
        print(f"❌ 启动后端服务时出错: {e}")
        return False

def open_frontend():
    """打开前端演示页面"""
    demo_path = Path(__file__).parent / "web" / "simple_demo.html"
    
    if demo_path.exists():
        file_url = f"file:///{demo_path.as_posix()}"
        print(f"🌐 打开演示页面: {file_url}")
        
        # 尝试打开浏览器
        try:
            webbrowser.open(file_url)
            print("✅ 演示页面已打开")
            return True
        except Exception as e:
            print(f"⚠️  无法自动打开浏览器: {e}")
            print(f"请手动打开: {file_url}")
            return True
    else:
        print("❌ 演示页面文件不存在")
        return False

def main():
    """主函数"""
    print("=" * 60)
    print("🎵 离线语言播放系统演示")
    print("=" * 60)
    
    # 检查依赖
    if not check_dependencies():
        return
    
    # 启动后端
    if not start_backend():
        print("\n❌ 无法启动后端服务，演示将使用模拟数据")
        input("按回车键继续打开演示页面...")
    
    # 打开前端
    if open_frontend():
        print("\n🎉 演示已启动!")
        print("\n📋 使用说明:")
        print("   1. 后端服务地址: http://127.0.0.1:8000")
        print("   2. API文档: http://127.0.0.1:8000/docs")
        print("   3. 演示页面包含语音合成、有声读物、播放器等功能")
        print("   4. 如果后端未连接，页面将使用模拟数据进行演示")
        
        print("\n按 Ctrl+C 退出演示")
        try:
            while True:
                time.sleep(1)
        except KeyboardInterrupt:
            print("\n👋 演示已退出")
    else:
        print("❌ 演示启动失败")

if __name__ == "__main__":
    main()